<template>
	<view>
		<view class="header">
			<uni-search-bar
				placeholder="请输入商品名称搜索"
				bgColor="#fff"
				:cancelButton="false"
				v-model="goodsName"
				@confirm="handleSearch"
				@clear="clearSearch"
			/>
		</view>
		<uni-list :border="true" v-if="goodsList.length > 0">
			<uni-list-item
				thumbSize="lg"
				v-for="(item, index) in goodsList"
				:key="index"
				:title="item.name" 
				:thumb="item.picture"
				:note="`规格：${item.weight}g`"
				:rightText="`售价：￥${item.sellPrice}`" 
			/>
			<uni-load-more :status="status" :icon-size="14" :content-text="contentText" v-if="goodsList.length > pageSize"></uni-load-more>
		</uni-list>
		<empty-view v-else></empty-view>
	</view>
</template>

<script>
	import EmptyView from "@/components/EmptyView"
	
	export default {
		components: {
			EmptyView
		},
		
		data() {
			return {
				goodsName: "",
				goodsList: [],
				status: 'more',
				contentText: {
					contentdown: '上拉加载更多~',
					contentrefresh: '加载中',
					contentnomore: '我是有底线的~'
				},
				pageNo: 1,
				pageSize: 10
			}
		},
		
		onShow() {
			let uid = uni.getStorageSync('uid');
			if(!uid) {
				uni.reLaunch({
					url:'/pages/user/login'
				})
			}
			
			this.getGoodsList()
		},
		
		onReachBottom() {
			if(this.status === 'more') {
				this.status = 'loading';
				this.getGoodsList();
			}
		},
		
		methods: {
			handleSearch() {
				this.pageNo = 1;
				this.goodsList = []
				this.getGoodsList()
			},
			
			clearSearch() {
				this.goodsName = ""
				this.getGoodsList()
			},
			
			getGoodsList() {
				uni.showLoading({
					title: '加载中...'
				})
				uni.request({
					url: getApp().globalData.apiUrl + '/card/api/v1/getGoodsList',
					data: {
						goodsName: this.goodsName,
						merchantId: uni.getStorageSync('mid'),
						pageNo: this.pageNo,
						pageSize: this.pageSize
					},
					success: res => {
						if(res.data.success) {
							let result = res.data.result
							let dataList = result.records
							let pn = this.pageNo;
							let datas = [];
							let status;
									
							if (pn == 1) {
								datas = dataList;
							} else {
								datas = this.goodsList.concat(dataList);
							}
								
							if (result.total > datas.length) {
								pn += 1;
								status = "more"
							} else {
								status = "no-more"
							} 
							
							this.setData({
								status,
								pageNo: pn,
								goodsList: datas,
							});
							
							uni.hideLoading()
						} else {
							uni.showToast({
								icon:'error',
								title: res.data.message
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.header{
		height: 120rpx;
		
		.add-box {
			height: 56px;
			display: flex;
			align-items: center;
		}
	}
</style>